﻿using System;
using System.Collections.Generic;
using System.Text;
using Wicresoft.EKA.NRemedy;
using System.Threading;
using System.Windows.Forms;
using Wicresoft.EKA.NRemedy.CodeGenerate;

namespace Wicresoft.EKA.NRemedy.CodeGenerator.WinForm
{
    public class GetFieldsThread : ARThread
    {

        public PushFieldsListDelegate GetFieldsCompeleted;

        private string formName = string.Empty;

        public void Start(string formName)
        {
            this.formName = formName;
            _thread = new Thread(GetListField);
            _thread.Start();
        }

        private void GetListField()
        {
            bool isSuccess = false;
            List<ARFieldDisplay> fields = new List<ARFieldDisplay>();
            string exceptionMessage = string.Empty;
            try
            {
                ARSchema asrsch = new ARSchema(_context);

                var result = asrsch.GetListField(formName);

                foreach (var r in result)
                {
                    if (r.IsDataField())
                    {
                        ARFieldDisplay f = new ARFieldDisplay(r);
                        fields.Add(f);
                    }
                }
                fields.Sort(new FieldDisplayComparer());
                GlobalCache.FieldCache = fields;
            }
            catch (Exception e)
            {
                exceptionMessage = e.Message;
            }

            if (GetFieldsCompeleted != null)
            {
                Control control = GetFieldsCompeleted.Target as Control;
                if (control != null)
                    control.Invoke(GetFieldsCompeleted, new object[] { fields });
                else
                    GetFieldsCompeleted(fields);
            }
        }
    }

    public class FieldDisplayComparer : IComparer<ARFieldDisplay>
    {
        public int Compare(ARFieldDisplay x, ARFieldDisplay y)
        {
            if (x.ID == y.ID)
            {
                return 0;
            }
            else if (x.ID > y.ID)
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }
    }
}
